package com.yimixian.app.adapter;

import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.cart.GoodsItemPresenter;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Banner;
import com.yimixian.app.model.FullLinearLayoutManager;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.model.MyLayoutManager;
import com.yimixian.app.model.MyLayoutManager2;
import com.yimixian.app.model.SortGoodsItem;
import com.yimixian.app.ui.HomeItemView;
import com.yimixian.app.ui.MyLinearLayout;
import com.yimixian.app.ui.PinnedSectionListView;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.Strings;
import com.ymx.sdk.util.ViewUtils;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeListViewAdapter extends BaseAdapter implements
        PinnedSectionListView.PinnedSectionListAdapter{

    public interface onItemViewClickListener {
        void onItemViewClick(View view, int sortPosition, int ChildPositin, Point startPoint);
    }

    private boolean isScrollUp;
    private int mLastPosition  = 2;
    private List<SortGoodsItem> mList;
    private Activity mActivity;
    private LayoutInflater mInflater;
    private Picasso picasso;
    private GoodsItemPresenter.OnPlusButtonClickListener mOnPlusButtonClickListener;
    private onItemViewClickListener mListener;
    private float dentity;
    public ListView mListView;

    public HomeListViewAdapter(Activity activity, List<SortGoodsItem> mList,
                               GoodsItemPresenter.OnPlusButtonClickListener plusButtonClickListener) {
        mActivity = activity;
        this.mList = mList;
        this.mOnPlusButtonClickListener = plusButtonClickListener;
        mInflater = LayoutInflater.from(activity);
        picasso = Picasso.with(mActivity);
        dentity = mActivity.getResources().getDisplayMetrics().density;
    }

    public void setList(List<SortGoodsItem> mList) {
        this.mList = mList;
        notifyDataSetChanged();
    }

    @Override
    public boolean isItemViewTypePinned(int viewType) {
        return viewType == SortGoodsItem.SECTION;
    }
    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        return mList.get(position).type;
    }

    @Override
    public int getCount() {
        return mList != null ? mList.size() : 0;
    }

    @Override
    public SortGoodsItem getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void isScrollUp(int dy){
        isScrollUp = dy > 0 ? true : false;
    }

    public void setMLastPosition(int mLastPosition){
        this.mLastPosition = mLastPosition;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.home_list_item2_3_0, parent, false);
//            convertView = mInflater.inflate(R.layout.home_list_item2, parent, false);
            holder = new ViewHolder();
            holder.itemView = (LinearLayout) convertView;
            holder.sortTitle = (TextView) convertView.findViewById(R.id.sort_title);
            holder.tv_more = (TextView) convertView.findViewById(R.id.tv_more);
            holder.linSort = (LinearLayout) convertView.findViewById(R.id.lin_sort);
            holder.ll_banner = (LinearLayout) convertView.findViewById(R.id.ll_banner);
//            holder.goodsView = (RecyclerView) convertView.findViewById(R.id.recycler_view);
//            FullLinearLayoutManager layoutManager = new FullLinearLayoutManager(mActivity);
//            layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//            holder.goodsView.setHasFixedSize(true);
//            holder.goodsView.setLayoutManager(layoutManager);
            holder.leftItem = (HomeItemView) convertView.findViewById(R.id.left_item);
            holder.rightItem = (HomeItemView) convertView.findViewById(R.id.right_item);
            holder.thirdItem = (HomeItemView) convertView.findViewById(R.id.third_item);
            holder.bottomLine = convertView.findViewById(R.id.bottom_line);
            holder.leftItem.setOnPlusButtonClickListener(mOnPlusButtonClickListener);
            holder.rightItem.setOnPlusButtonClickListener(mOnPlusButtonClickListener);
            holder.thirdItem.setOnPlusButtonClickListener(mOnPlusButtonClickListener);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        initData(holder, position);
        return convertView;
    }

    public class ViewHolder {
        public LinearLayout itemView;
        public TextView sortTitle, tv_more;
        public LinearLayout linSort, ll_banner;
        public HomeItemView leftItem, rightItem, thirdItem;
        public View bottomLine;
//        public RecyclerView goodsView;
        private int height;
    }

    // 初始化数据
    public void initData(ViewHolder holder, final int position) {
        if (position >= mList.size()){
            return;
        }
        final SortGoodsItem sortGoodsItem = mList.get(position);
//        makeAnimation(holder, sortGoodsItem, position);
        if (sortGoodsItem.type == SortGoodsItem.SECTION){//分类标题
            holder.bottomLine.setVisibility(View.GONE);
            setSectionTitle(sortGoodsItem.name, holder);
            //设置查看更多点击
            holder.tv_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!Strings.isNullOrEmpty(sortGoodsItem.id)) {
                        Map<String, String> hashMap = new HashMap<>();
                        hashMap.put("ID", sortGoodsItem.id);
                        DateUtil.setCityUMeng(hashMap, UMengConstants.NEW_HOME_MORE_BTN);
                        String url = "ymxian://show_section?section_id=" + sortGoodsItem.id;
                        Intent intent = new Intent(mActivity, WebViewActivity.class);
                        intent.putExtra(WebViewActivity.EXTRA_URL, url);
                        mActivity.startActivity(intent);
                    }
                }
            });
//            holder.goodsView.setVisibility(View.GONE);
        }else if (sortGoodsItem.type == SortGoodsItem.ITEM){
            //是否显示底线
            if(mList.size() > position + 1 &&
                    mList.get(position + 1).type == SortGoodsItem.SECTION){
                holder.bottomLine.setVisibility(View.VISIBLE);
            }else {
                holder.bottomLine.setVisibility(View.GONE);
            }
            holder.bottomLine.setVisibility(View.VISIBLE);
            setItem(sortGoodsItem, holder, position);
        }
    }

    /**
     * 分类的标题section
     * @param name
     */
    void setSectionTitle(String name, ViewHolder holder){
//        holder.linSort.setVisibility(View.VISIBLE);
        holder.sortTitle.setText(name == null ? "" : name);
    }

    private Map<Integer, Integer> heightMap = new HashMap<>();

    /**
     * 分类下面的item
     * @param sortGoodsItem
     * @param holder
     */
    void setItem(final SortGoodsItem sortGoodsItem, final ViewHolder holder, final int position){
        holder.linSort.setVisibility(View.GONE);
//        holder.goodsView.setVisibility(View.VISIBLE);
        final List<GoodsItem> rowData = sortGoodsItem.rowData;
//        if(rowData == null || rowData.size() == 0){
//            holder.goodsView.setVisibility(View.GONE);
//        }else{
//            GoodsAdapter adapter = (GoodsAdapter) holder.goodsView.getAdapter();
//            if(adapter == null){
//                holder.goodsView.setAdapter(new GoodsAdapter(rowData));
//            }else{
//                adapter.update(rowData);
//            }
//        }

        GoodsItem[] goodsItems = new GoodsItem[3];
        if(rowData != null){
            for (int i = 0; i < rowData.size(); i++) {
                if(i == goodsItems.length)
                    break;
                goodsItems[i] = rowData.get(i);
            }
        }

        holder.leftItem.bindData(goodsItems[0], Constants.STATE_HOMENEWFRAGMENT_BUTTON_BROADCAST, true, false);
        holder.rightItem.bindData(goodsItems[1],Constants.STATE_HOMENEWFRAGMENT_BUTTON_BROADCAST, true, false);
        holder.thirdItem.bindData(goodsItems[2],Constants.STATE_HOMENEWFRAGMENT_BUTTON_BROADCAST, true, false);
//        holder.leftItem.bindData(sortGoodsItem.leftGoodsItem, Constants.STATE_HOMENEWFRAGMENT_BUTTON_BROADCAST, true, false);
//        holder.rightItem.bindData(sortGoodsItem.RightGoodsItem,Constants.STATE_HOMENEWFRAGMENT_BUTTON_BROADCAST, true, false);
//        holder.thirdItem.bindData(sortGoodsItem.thirdGoodsItem,Constants.STATE_HOMENEWFRAGMENT_BUTTON_BROADCAST, true, false);
        //banner
        float mScreenWidth = mActivity.getResources().getDisplayMetrics().widthPixels;
        if(sortGoodsItem.mBannerItems != null && sortGoodsItem.mBannerItems.size() > 0 && position == 1){
            holder.ll_banner.setVisibility(View.VISIBLE);
            holder.ll_banner.removeAllViews();
            List<Banner> items = sortGoodsItem.mBannerItems;
            for(int i = 0; i < items.size(); i++){
                final Banner each = items.get(i);
                ImageView iv = new ImageView(mActivity);
                iv.setScaleType(ImageView.ScaleType.CENTER);
                iv.setAdjustViewBounds(true);
                int size = (int)(mScreenWidth / 1.2f);
                String imgUrl = DataManager.getInstance().getImageUrl(each.img, size);
                Picasso picasso = Picasso.with(mActivity);
                picasso.load(imgUrl).placeholder(R.drawable.pic_banner_default_bg).into(iv);
//                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int) (120 * dentity));
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp.setMargins(0, 0, 0, (int) (10 * dentity));
                holder.ll_banner.addView(iv, lp);
                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mActivity, WebViewActivity.class);
                        intent.putExtra(WebViewActivity.EXTRA_URL, each.introUrl);
                        mActivity.startActivity(intent);
                    }
                });
            }
        }else{
            holder.ll_banner.setVisibility(View.GONE);
        }
    }


    public void makeAnimation(ViewHolder holder, SortGoodsItem sortGoodsItem,
                              int position){
        if (sortGoodsItem == null) return;
        if (isScrollUp && sortGoodsItem.type == SortGoodsItem.ITEM){
            if (position > mLastPosition) {
                Animator anim = getAnimation(holder.itemView);
                anim.setDuration(500).start();
                mLastPosition = position;
            } else {
                ViewUtils.clear(holder.itemView);
            }
        }else{
            mLastPosition = position;
            ViewUtils.clear(holder.itemView);
        }
    }

    int translateY = 200;
    public Animator getAnimation(View view){
        return ObjectAnimator.ofFloat(view, "translationY", translateY, 0);
    }

    class GoodsAdapter extends RecyclerView.Adapter{

        private List<GoodsItem> list;
        private float dentity;

        public GoodsAdapter(List<GoodsItem> list) {
            this.list = list;
            dentity = mActivity.getResources().getDisplayMetrics().density;
        }

        public void update(List<GoodsItem> list){
            this.list = list;
            notifyDataSetChanged();
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
//            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.home_item_parent, null);
//            HomeItemView homeView = new HomeItemView(mActivity);
//            view.setLayoutParams(lp);
            return new GoodViewHolder(new HomeItemView(mActivity));
//            return new GoodViewHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
            GoodViewHolder holder = (GoodViewHolder) viewHolder;
            GoodsItem good = list.get(i);
            holder.homeView.setOnPlusButtonClickListener(mOnPlusButtonClickListener);
            holder.homeView.bindData(good, Constants.STATE_HOMENEWFRAGMENT_BUTTON_BROADCAST, true, true);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            holder.homeView.setLayoutParams(lp);
            if(i < list.size() - 1)
                lp.setMargins(0, 0, (int) (10 * dentity), 0);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class GoodViewHolder extends RecyclerView.ViewHolder{
            public View rootView;
            public HomeItemView homeView;

            public GoodViewHolder(View itemView) {
                super(itemView);
                homeView = (HomeItemView) itemView;
//                homeView = (HomeItemView) itemView.findViewById(R.id.v_home);
            }


        }

    }

}
